﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace video
{
    public partial class VideoDownloadForm : Form
    {
        System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string dllName = args.Name.Contains(",") ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");
            dllName = dllName.Replace(".", "_");
            if (dllName.EndsWith("_resources")) return null;
            System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
            byte[] bytes = (byte[])rm.GetObject(dllName);
            return System.Reflection.Assembly.Load(bytes);
        }

        public VideoDownloadForm()
        {
            //在InitializeComponent()之前调用
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            InitializeComponent();
            savePathTextBox.Text = Directory.GetCurrentDirectory().ToString() + Path.DirectorySeparatorChar + "video";
            folderBrowserDialog.SelectedPath = folderBrowserDialog.SelectedPath;
        }

        private async void GetDownloadVideoResult(object obj)
        {
            Dictionary<string, string> dict = obj as Dictionary<string, string>;
            dict.TryGetValue("url", out string url);
            dict.TryGetValue("savePath", out string savePath);
            bool result = await Video.Download(url, savePath);
            if (!result)
            {
                MessageBox.Show("视频下载失败");
                return;
            }
            System.Diagnostics.Process.Start("explorer.exe", savePathTextBox.Text);
        }

        /// <summary>
        /// 触发下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DownloadVideo(object sender, EventArgs e)
        {
            try
            {
                // 获取链接
                string url = urlTextBox.Text.Trim();
                if (url.Length == 0)
                {
                    string message = String.Format("{0}不能为空", this.label1.Text);
                    MessageBox.Show(message);
                    return;
                }
                string savePath = savePathTextBox.Text;
                Thread thread = new Thread(GetDownloadVideoResult)
                {
                    IsBackground = true
                };
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add("url", url);
                dict.Add("savePath", savePath);
                thread.Start(dict);
            }
            catch (Exception exception) {
                using (FileStream fileStream = new FileStream("exception.txt", FileMode.Append, FileAccess.Write))
                {
                    string exception_str = exception.Message + "\n";
                    exception_str += exception.Source + "\n";
                    exception_str += exception.StackTrace + "\n";
                    exception_str += "\n";
                    byte[] byteArray = System.Text.Encoding.Default.GetBytes(exception_str);
                    fileStream.Write(byteArray, 0, byteArray.Length);
                }
                MessageBox.Show(String.Format("程序运行异常：{0}", exception.Message));
            }
            return;
        }

        /// <summary>
        /// 选择下载目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowDirectoryEntry(object sender, EventArgs e)
        {
            folderBrowserDialog.ShowDialog();
            savePathTextBox.Text = folderBrowserDialog.SelectedPath;
            folderBrowserDialog.Dispose();
        }

        /// <summary>
        /// 过滤输入链接空白字符
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UrlTextBoxTextChanged(object sender, EventArgs e)
        {
            urlTextBox.Text = urlTextBox.Text.Trim();
        }
    }
}
